<template>
  <el-dialog
    v-dialogDrag
    :visible="isDialogVisible"
    :title="titleName"
    center
    width="50%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader
      slot="title"
      :title="titleName"
      :style-type="$store.state.app.dialogType"
    />
    <div
      v-loading="saveloading"
      class="filter-container filter-params"
    >
      <one-table-template
        ref="multipleTable"
        :dynamic-api-config="apiConfig"
        :dynamic-buttons="dynamicButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-cols="dynamicTableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :refresh-table-key="refreshTableKey"
        :callback-obj="callbackObj"
      />
    </div>
  </el-dialog>
</template>

<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    popupsState: {
      type: String,
      default: ''
    },
    isDialogVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '时机设置',
      saveloading: false,
      modelCode: [],
      month: '',
      refreshTableKey: '0',
      // table表格查询API配置对象
      apiConfig: {},
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '门店名称：',
              codeField: 'storeName',
              isRequire: true,
              component: () => import('./plan/index'),
              disabled: true,
              parentFileds: 'disabled:isEdit-storeName--true',
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey2',
              labelName: '22位码：',
              codeField: 'ttCode',
              isRequire: true,
              disabled: true,
              parentFileds: 'disabled:isEdit-ttCode--true',
              component: () => import('./config/index'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
              // validrule: {
              //   minlength: 22,
              //   maxlength: 22,
              //   resectMessage: {
              //     minlength: '编码为22位!',
              //     maxlength: '编码为22位!'
              //   }
              // }
            },
            {
              compKey: 'compKey3',
              labelName: '制定月份：',
              codeField: 'makingMonth',
              isRequire: true,
              disabled: true,
              parentFileds: 'disabled:isEdit-makingMonth--true',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'month',
              dateOptionsType: '3', // 禁用当前日期之前的日期
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey4',
              labelName: '制定截止日期：',
              codeField: 'endDate',
              isRequire: true,
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'date',
              dateOptionsType: '3', // 禁用当前日期之前的日期
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey5',
              labelName: '计划月份：',
              codeField: 'plan',
              code: 'formField.planMonth',
              component: () => import('@/components/org/checkBox/month'),
              type: 'checkbox',
              isMust: true,
              span: this.spanNum()
            }
          ],
      // form 的表单对象
      formField:
        {
          isEdit: '',
          storeName: '',
          ttCode: '',
          makingMonth: '',
          endDate: '',
          plan: '',
          dlrId: [],
          planMonth: []
        },
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'save',
              clickEvent: () => this.saves(),
              text: '保存'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(),
              text: '取消'
            },
            {
              compKey: 'btnKey3',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              name: 'reset',
              clickEvent: () => this.resetData(),
              text: '清除',
              position: 'right'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [],

      // 单表格模版页面组件回调事件
      callbackObj: {
        // 手动勾选时会触发该事件（多选时）
        onCheckSelect: (selection) => {
          console.log(selection)
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  // 监听传入参数变化
  watch: {
    isDialogVisible: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            setTimeout(() => {
              const comp = this.$refs['multipleTable'].$refs['truecompKey2'][0]
              if (this.popupsState === 'edit') {
                const {
                  dlrShortName, makingMonth, endDate, plan, dlrId, planMonth, proportionSetId, updateControlId,
                  carConfigCode, carColorCode, carIncolorCode,
                  optionalPagCode, carSeriesCode, ttCode, carSeriesId, carConfigId, carIncolorId, carOptionalpagId, carColorId
                } = this.dataForForm
                this.formField.makingMonth = '1970-01'
                comp.innerForm = {
                  carSeriesCn: carSeriesId, ttCode, carSeriesCode,
                  carConfigCode, carColorCode, carIncolorCode, optionalPagCode, carConfigId, carIncolorId, carOptionalpagId, carColorId
                }
                this.formField = Object.assign(this.formField, { ttCode, makingMonth, endDate, plan, dlrId, planMonth, proportionSetId, updateControlId })
                this.formField.storeName = dlrShortName
                this.formField.isEdit = '1'
              } else {
                comp.innerForm = {}
              }
            }, 0)
          })
        }
      },
      immediate: true
    },
    'formField.makingMonth': {
      deep: true,
      handler: function(newV, oldV) {
        console.log(newV)
        let year
        const tmpVal = newV || ''
        year = (tmpVal.split('-'))[0]
        this.month = (tmpVal.split('-'))[1]
        let plan1 = `${this.month[0]}` + `${Number(this.month[1]) + 1}`
        let plan2 = `${this.month[0]}` + `${Number(this.month[1]) + 2}`
        let plan3 = `${this.month[0]}` + `${Number(this.month[1]) + 3}`
        if (Number(this.month[1]) >= 1) {
          if (Number(this.month[1]) === 7) {
            plan3 = `${Number(this.month[1]) + 3}`
          }
          if (Number(this.month[1]) === 8) {
            plan2 = `${Number(this.month[1]) + 2}`
            plan3 = `${Number(this.month[1]) + 3}`
          }
          if (Number(this.month[1]) === 9) {
            plan1 = `${Number(this.month[1]) + 1}`
            plan2 = `${Number(this.month[1]) + 2}`
            plan3 = `${Number(this.month[1]) + 3}`
          }
          this.formField.plan = `${plan1},${plan2},${plan3}`
          let month = []
          const arr = []
          month = this.formField.plan.split(',')
          for (let i = 0; i < month.length; i++) {
            arr[i] = year + '-' + month[i]
          }
          this.formField.planMonth = arr
        }
        if (Number(this.month) === 10) {
          plan3 = '01'
        }
        if (Number(this.month) === 11) {
          plan2 = '01'
          plan3 = '02'
        }
        if (Number(this.month) === 12) {
          plan1 = '01'
          plan2 = '02'
          plan3 = '03'
          year = parseInt(year)
          year += 1
        }
        this.formField.plan = `${plan1},${plan2},${plan3}`
        let month = []
        const arr = []
        month = this.formField.plan.split(',')
        for (let i = 0; i < month.length; i++) {
          arr[i] = year.toString() + '-' + month[i]
        }
        this.formField.planMonth = arr
      }
    }
  },

  mounted() {},

  methods: {
    // form表单组件每个元素所占栅格栏数每行24格
    spanNum() {
      return 24
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },

    // 保存
    saves() {
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        this.saveloading = true
        // this.formField.makingMonth = this.formField.formulateMonth
        // this.formField.endDate = this.formField.endMonth
        // this.formField.ttCode = this.formField.Numcode
        const data = JSON.parse(JSON.stringify(this.formField))
        this.$emit('save', data)
      }
    },

    // 清除
    resetData() {
      this.reset()
      this.formField.storeName = ''
      this.formField.code = ''
      this.formField.formulateMonth = ''
      this.formField.endMonth = ''
      this.formField.planMonth = ''
    }
  }
}
</script>
